package DataStructures;

/*
 * Binary tree with insertions and runners
 */
public class BinaryTree <T extends Comparable<T>> {
	
	private TNode<T> root;
	
	public BinaryTree(){
		
		root = null;
	}
	
	public void addLeft(TNode<T> node, T e)
	{
		if(node == null)
		  System.out.println("Null node");
		else
		  node.setLeft(new TNode<T>(e));
	}

	public void addRight(TNode<T> node, T e)
	{
		if(node == null)
		  System.out.println("Null node");
		else
		  node.setRight(new TNode<T>(e));
	}

	public void insert(T e)
	{
		TNode<T> runner = null;
		TNode<T> ant= null;
		if(root == null)
		   root = new TNode<T>(e);
		else
		{
			runner = root;
			while(runner!=null && e.compareTo(runner.getInfo())!= 0){
				ant = runner;
				if (e.compareTo(runner.getInfo())<0)
					runner=runner.getLeft();
				else
					runner=runner.getRight();
			}
			if(runner == null)
				if(e.compareTo(ant.getInfo())<0)
				   addLeft(ant, e);
				else
				   addRight(ant, e);
	    }
	}

	public void runInOrder(TNode<T> node)
	{
		if(node != null)
		{
			runInOrder(node.getLeft());
			System.out.println(node.getInfo());
			runInOrder(node.getRight());
		}

	}

	public void runInPreorder(TNode<T> nodo)
	{
		if(nodo != null)
		{
			System.out.println(nodo.getInfo());
			runInPreorder(nodo.getLeft());
			runInPreorder(nodo.getRight());
		}

	}
	
	public void runInPostorder(TNode<T> nodo)
	{
		if(nodo != null)
		{
			runInPostorder(nodo.getLeft());
			runInPostorder(nodo.getRight());
			System.out.println(nodo.getInfo());
		}

	}

	public TNode<T> getRoot()
	{
		return root;
	}
}
